import React, { useEffect, useCallback, useState } from 'react';
import { Table } from 'antd';
import { TableProps } from 'antd/lib/table';
import styles from './styles.less';

type ServiceParams = {
  page: number,
  limit: number;
  [key: string]: unknown;
}

type ServiceOutput = {
  totalCount: number;
  list: any[];
}

type Service = (para: ServiceParams) => Promise<ServiceOutput>;

type IProps = TableProps<any> & {
  service?: Service;
  onLoad?: (cb: () => void) => void;
}

const TablePro: React.FC<IProps> = props => {
  const { service, onLoad, ...rest } = props;
  const [list, setList] = useState<any[]>([]);
  const [page, setPage] = useState<number>(1);
  const [total, setTotal] = useState<number>(0);
  const [pageSize, setPageSize] = useState<number>(10);
  const [loading, setLoading] = useState<boolean>(false);

  const onFetchList = useCallback((page: number, limit: number) => {
    const params = { page: page, limit: limit };
    setLoading(true);
    service?.(params).then((res) => {
      setPage(page || 0);
      setList(res.list || []);
      setTotal(res.totalCount || 0);
    }).finally(() => {
      setLoading(false);
    });
  }, []);

  const onRefresh = useCallback(() => {
    onFetchList(1, pageSize);
  }, []);

  const onPageChange = useCallback((page: number, limit: number) => {
    setPageSize(limit);
    onFetchList(page, limit);
  }, []);

  useEffect(() => {
    onRefresh();
    onLoad?.(onRefresh);
  }, []);

  const pagination: any = total ? {
    total: total,
    current: page,
    pageSize: pageSize,
    onChange: onPageChange,
  } : false;

  return (
    <Table
      bordered
      rowKey="id"
      loading={loading}
      dataSource={list}
      pagination={pagination}
      className={styles.table_center}
      {...rest}
    />
  );
};

TablePro.defaultProps = {
  service: async () => {
    return { totalCount: 0, list: [] };
  },
};

export default TablePro;
